#!/bin/bash

readonly OPERATION=$1
readonly ROLE=$2
readonly SCOPE=$3

VIP=192.168.60.111
INF=ens33

# 检查 VIP 是否已存在[0：不存在 1:已存在]
check_vip_exists(){
  local chk_value=$(sudo ip addr show dev ${INF} to ${VIP})
  if [ -n "$chk_value" ];then
    return 1
  else
    return 0
  fi
}

# arping检查 VIP 是否已被占用[0：未占用 1:已占有]
check_vip_arp(){
  sudo arping -c 1 -I ${INF} ${VIP}
  if [ $? -eq 0 ];then
    return 1
  else
    return 0
  fi
}

# 添加 VIP
cmd_vip_add(){
  if check_vip_exists && check_vip_arp;then
    sudo ip addr add  ${VIP} dev ${INF}
    echo "$(date "+%Y-%m-%d %H:%M:%S %z") VIP ${VIP} added"  >> /app/pgsql/patroni/log/patroni.log
  else
    echo "$(date "+%Y-%m-%d %H:%M:%S %z") VIP ${VIP} already be used,please check!" >> /app/pgsql/patroni/log/patroni.log
  fi
}

# 删除 VIP
cmd_vip_del(){
  echo "$(date "+%Y-%m-%d %H:%M:%S %z") 执行删除 VIP 操作" >> /app/pgsql/patroni/log/patroni.log
  if ! check_vip_exists;then
    sudo ip addr del ${VIP}/32 dev ${INF}
    echo "$(date "+%Y-%m-%d %H:%M:%S %z") VIP ${VIP} removed" >> /app/pgsql/patroni/log/patroni.log
  else
    echo "$(date "+%Y-%m-%d %H:%M:%S %z") VIP ${VIP} not exists!" >> /app/pgsql/patroni/log/patroni.log
  fi
}

# 设置备份相关信息
set_backup_on_master(){
  # 被拉升为主则需要将备份挂载在这台机器上
  echo "$(date "+%Y-%m-%d %H:%M:%S %z") 首次或切换，配置主实例备份信息..." >> /app/pgsql/patroni/log/patroni.log
  /app/pgsql/backup/backup_pgbackrest.sh "create" >> /app/pgsql/patroni/log/patroni.log
  /app/pgsql/backup/backup_pgbackrest.sh "check" >> /app/pgsql/patroni/log/patroni.log
  /app/pgsql/backup/backup_pgbackrest.sh "add_crontab" >> /app/pgsql/patroni/log/patroni.log
}

# 删除非主库上的备份定时任务
del_backup_on_slave(){
  
  local chk_value=$(cat \/etc\/crontab |grep backup_pgbackrest|wc -l)
  if [ $chk_value -gt 0 ];then
     #echo "$(date "+%Y-%m-%d %H:%M:%S %z") 删除实例备份crontab配置..." >> /app/pgsql/patroni/log/patroni.log
     /app/pgsql/backup/backup_pgbackrest.sh "del_crontab" >> /app/pgsql/patroni/log/patroni.log
  fi
}

echo "$(date "+%Y-%m-%d %H:%M:%S %z") This is patroni callback $OPERATION $ROLE $SCOPE" >> /app/pgsql/patroni/log/patroni.log

case $OPERATION in
 on_stop)
 cmd_vip_del
 del_backup_on_slave
 ;;
 on_reload)
 if [[ $ROLE == 'master' ]];then
 
   echo "$(date "+%Y-%m-%d %H:%M:%S %z") 进入on_reload,重启patroni防止拉升为错误的主..." >> /app/pgsql/patroni/log/patroni.log
   systemctl restart patroni
   cmd_vip_add 
   set_backup_on_master
 else
   cmd_vip_del
   del_backup_on_slave
 fi
 ;;
 on_start | on_restart | on_role_change)
 if [[ $ROLE == 'master' || $ROLE == 'standby_leader' ]]; then
   cmd_vip_add 
   # 设置主服务器上的备份信息
   set_backup_on_master
 else
   cmd_vip_del
   del_backup_on_slave 
 fi
 ;;
 *)
 usage
 ;;
esac
